class CollisionSystem extends System {
	constructor(world) {
		super(world);
	}

    getPlayerEntity() {
        for (const entity of this.getWorld().getEntities()) {
            if (entity.getComponent(PlayerControllerComponent)) {
                return entity;
            }
        }
    }

    execute() {
        const player = this.getPlayerEntity();
        for (const entity of this.getWorld().getEntities()) {
            if (entity !== player && CollisionSystem.collide(player, entity)) {
                this.getWorld().getMessageManager().notify({
                    type: 'COLLISION',
                    target: entity,
                });
            }
        }
    }

	static collide(a, b) {
        const circleCollisionComponentA = a.getComponent(CircleCollisionComponent);
        const positionComponentA = a.getComponent(PositionComponent);
        const circleCollisionComponentB = b.getComponent(CircleCollisionComponent);
        const positionComponentB = b.getComponent(PositionComponent);
        if (circleCollisionComponentA && positionComponentA && circleCollisionComponentB && positionComponentB) {
            const {x: xa, y: ya} = positionComponentA;
            const {x: xb, y: yb} = positionComponentB;
            const {radius: ra} = circleCollisionComponentA;
            const {radius: rb} = circleCollisionComponentB;

            return (Math.pow(xa - xb, 2) + Math.pow(ya - yb, 2)) <= Math.pow(ra + rb, 2);
        }

        return false;
    }
}




// prepare() {
//    const targets = [];
//    const collisions = {};
//     for (const entity of this.getWorld().getEntities()) {
//         const circleCollisionComponent = entity.getComponent(CircleCollisionComponent);
//         const positionComponent = entity.getComponent(PositionComponent);
//         if (circleCollisionComponent && positionComponent) {
//             const uuid = circleCollisionComponent.getUuid();
//             targets.push({
//                 uuid,
//                 x: positionComponent.x,
//                 y: positionComponent.y,
//                 r: circleCollisionComponent.radius,
//             });
//             collisions[uuid] = [];
//         }
//     }
//     return {targets, collisions};
// }

// execute() {
//     const {targets, collisions} = this.prepare();
//     for (let i = 0; i < targets.length; i++) {
//         const a = targets[i];
//         for (let j = i + 1; j < targets.length; j++) {
//             const b = targets[j];
//             if (CollisionSystem.ball2ball(a, b)) {
//                 collisions[a.uuid].push(b.uuid);
//                 collisions[b.uuid].push(a.uuid);
//             }
//         }
//     }
//     this._collisions = collisions;
// }